<?php

namespace app\admin\controller\user;

use app\admin\model\ClassAddress;
use app\admin\model\ClubDtl;
use app\admin\model\IdentityInfo;
use app\admin\model\Sharpshooter;
use app\admin\model\TeacherClass;
use app\admin\model\TeacherCourseDisplay;
use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname,mobile';
    protected $selectpageFields = 'id,nickname,mobile';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 处理身份搜索的特殊逻辑
            $identitySearch = false;
            $identityValue = '';

            $filter = json_decode($this->request->get("filter", ''), true);
            $op     = json_decode($this->request->get("op", '', 'trim'), true);
            if (isset($filter['identity.identity_type'])&&$filter['identity.identity_type'] == '普通用户') {
                $identityValue = $filter['identity.identity_type'];
                if($identityValue == '普通用户'){
                    $identitySearch = true;
                }
                unset($filter['identity.identity_type']);
                unset($op['identity.identity_type']);
                // 重新设置请求参数
                $this->request->get(['filter' => json_encode($filter)]);
                $this->request->get(['op' => json_encode($op)]);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $sort_count = '';
            if($sort == 'user.invited_count'){
                $sort_count = 'invited_count';
            }
            // 如果搜索的是普通用户，需要特殊处理
            if ($identitySearch && $identityValue == '普通用户') {
                // 使用 LEFT JOIN 来查找没有身份信息的用户
                $list = $this->model
                    ->join('identity_info identity', 'user.id = identity.user_id', 'LEFT')
                    ->where($where)
                    ->where(function($query) {
                        $query->whereNull('identity.user_id')
                              ->whereOr('identity.identity_type', 'null')
                              ->whereOr('identity.identity_type', '');
                    });
            } else {
                // 正常查询，使用关联
                $list = $this->model
                    ->with(['group','identity'])
                    ->where($where);
            }
            
            // 添加邀请人数统计字段
            $list = $list->field('user.*, (SELECT COUNT(*) FROM fa_user u2 WHERE u2.p_user_id = user.id) as invited_count');
            
            // 处理排序逻辑
            if ($sort_count == 'invited_count') {
                // 按邀请人数排序，使用子查询
                if ($order == 'desc') {
                    $list = $list->orderRaw('(SELECT COUNT(*) FROM fa_user u2 WHERE u2.p_user_id = user.id) DESC');
                } else {
                    $list = $list->orderRaw('(SELECT COUNT(*) FROM fa_user u2 WHERE u2.p_user_id = user.id) ASC');
                }
            } else {
                $list = $list->order($sort, $order);
            }
            
            // 如果进行了身份搜索，需要选择正确的字段并处理关联数据
            if ($identitySearch) {
                $list = $list->field('user.*,COALESCE(identity.identity_type,"普通用户") as identity_type, (SELECT COUNT(*) FROM fa_user u2 WHERE u2.p_user_id = user.id) as invited_count');
                
                // 处理身份搜索时的排序逻辑
                if ($sort_count == 'invited_count') {
                    if ($order == 'desc') {
                        $list = $list->orderRaw('(SELECT COUNT(*) FROM fa_user u2 WHERE u2.p_user_id = user.id) DESC');
                    } else {
                        $list = $list->orderRaw('(SELECT COUNT(*) FROM fa_user u2 WHERE u2.p_user_id = user.id) ASC');
                    }
                } else {
                    $list = $list->order($sort, $order);
                }

                $list = $list->paginate($limit);
                
                // 手动加载关联数据
                foreach ($list as $item) {
                    $item->group = \app\admin\model\UserGroup::get($item->group_id);
                    $item->identity = \app\admin\model\IdentityInfo::where('user_id', $item->id)->find();
                }
            } else {
                $list = $list->paginate($limit);
            }

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Selectpage的实现方法
     */
    public function selectpage()
    {
        //设置过滤方法 - 移除htmlspecialchars以避免中文编码问题
        $this->request->filter(['trim', 'strip_tags']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'nickname';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->field('id,nickname,mobile')
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                $result = [
                    $primarykey => $item[$primarykey] ?? '',
                    $field      => $item[$field] ?? '',
                    'nickname'  => $item['nickname'] ?? '',
                    'mobile'    => $item['mobile'] ?? '',
                ];
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
        }
        $result = ['total' => $total, 'list' => $list];
        return json($result);
    }

    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            // 检查用户名是否已存在
            if (!empty($params['username'])) {
                $existingUser = $this->model->where('username', $params['username'])->find();
                if ($existingUser) {
                    $this->error('登陆账户已存在，请使用其他登陆账户');
                }
            }
            
            // 检查手机号是否已存在
            if (!empty($params['mobile'])) {
                $existingMobile = $this->model->where('mobile', $params['mobile'])->find();
                if ($existingMobile) {
                    $this->error('手机号已存在，请使用其他手机号');
                }
            }
            
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $identity_type = $params['identity_type'];
            unset($params['identity_type']);
            
            // 生成邀请码
            $params['invitation_code'] = \app\admin\model\User::generateInvitationCode();
            
            // 如果有邀请者，设置邀请时间
            if (!empty($params['p_user_id'])) {
                $params['invitation_time'] = date('Y-m-d H:i:s');
            }
            
            $result = $this->model->allowField(true)->save($params);
            $newId = $this->model->id;
            Db::commit();
            if($identity_type!='普通用户'){
                $identity_info = new IdentityInfo();
                $identity_info->default_add($params['mobile'],$newId,$identity_type);
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $params = $this->request->post('row/a');
        if(isset($params['nickname'])&&$params['nickname']){
            $user_id = $row['id'];
            IdentityInfo::where(['user_id'=>$user_id])->update(['name'=>$params['nickname']]);
        }
        
        // 检查邀请者是否发生变化，如果变化则更新邀请时间
        if (isset($params['p_user_id']) && $params['p_user_id'] != $row['p_user_id']) {
            $params['invitation_time'] = date('Y-m-d H:i:s');
        }
        
        return $this->editss($ids,$params);
    }
    public function editss($ids = null,$params = [])
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        IdentityInfo::where(['user_id'=>$row['id']])->delete();
        ClassAddress::where(['user_id'=>$row['id']])->delete();
        Sharpshooter::where(['user_id'=>$row['id']])->delete();
        TeacherCourseDisplay::where(['user_id'=>$row['id']])->delete();
        ClubDtl::where(['user_id'=>$row['id']])->update(['user_id'=>0]);
        TeacherClass::where(['teacher_id'=>$row['id']])->delete();;
        TeacherClass::where(['user_id'=>$row['id']])->delete();
        $this->success();
    }

    /**
     * 邀请人列表
     */
    public function invited($ids = null)
    {
        if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        $invitedUsers = \app\admin\model\User::getInvitedUsers($ids);
        $user = \app\admin\model\User::get($ids);
        
        $this->view->assign('invitedUsers', $invitedUsers);
        $this->view->assign('user', $user);
        return $this->view->fetch();
    }

}
